import '../public-path'
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import {renderWithQiankun, qiankunWindow} from 'vite-plugin-qiankun/dist/helper'

let app = null

function render(props = {}) {
    const {container} = props
    app = createApp(App)
    app.use(router)
    app.mount(container ? container.querySelector('#app') : '#app')
}

// 独立运行时直接渲染
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
    render()
}

// 导出 qiankun 生命周期钩子
export async function bootstrap() {
    console.log('子应用启动')
}

export async function mount(props) {
    console.log('子应用挂载', props)
    render(props)
}

export async function unmount(props) {
    console.log('子应用卸载')
    if (app) {
        app.unmount()
        app._container.innerHTML = ''
        app = null
    }
}

// 使用 vite-plugin-qiankun 的辅助方法
renderWithQiankun({
    mount(props) {
        console.log('vite-plugin-qiankun mount')
        render(props)
    },
    bootstrap() {
        console.log('vite-plugin-qiankun bootstrap')
    },
    unmount(props) {
        console.log('vite-plugin-qiankun unmount')
        if (app) {
            app.unmount()
            app._container.innerHTML = ''
            app = null
        }
    },
    update(props) {
        console.log('vite-plugin-qiankun update', props)
    }
})
